package org.lee.merge.impl;

import org.lee.export.model.ApiResult;
import org.lee.export.model.ResultCode;
import org.lee.export.utils.FileUtils;
import org.lee.merge.IImageMergeStrategy;
import org.lee.merge.IImageMerger;
import org.lee.merge.MergeException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jackielee
 * @version 1.0
 * @description ImageMerger
 * @date 2021/5/7
 **/
public class ImageMerger implements IImageMerger {

    private final IImageMergeStrategy imageMergeStrategy;

    public ImageMerger(IImageMergeStrategy imageMergeStrategy) {
        this.imageMergeStrategy = imageMergeStrategy;
    }

    @Override
    public ApiResult merge(String path, String fileName) {
        List<File> files = FileUtils.getFiles(path).stream().filter(f -> f.isFile() && FileUtils.checkImage(f)).collect(Collectors.toList());
        if (files.isEmpty()) {
            return ApiResult.failure(ResultCode.FAILURE, "not any image to merge");
        }
        try {
            BufferedImage img = imageMergeStrategy.draw(files);
            ImageIO.write(img, "png", new File(fileName));
        } catch (MergeException | IOException e) {
            return ApiResult.failure(ResultCode.ERROR, e.getMessage());
        }
        return ApiResult.success();
    }
}
